<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<!--form上传文件-->
<h1>excel上传,写入数据库,利用jxl包操作</h1>
<h2>Form上传文件</h2>
<form action="/test/import_jxl" method="post" enctype="multipart/form-data">
    <input id="formfile" accept="application/vnd.ms-excel" type="file" name="files" multiple="multiple"  onchange="fileFormSelectChange()"/>
    <input type="submit" value="文件上传" style="margin: 10px"/>
</form>
<!--AJAX上传文件-->
<br/>
<h2>AJAX上传文件</h2>
<form name="form2" id="form2">
    <input id="ajaxfile" type="file" name="files" multiple="multiple" onchange="fileAjaxSelectChange()" />
    <input type="button" id="ajaxUpload" value="文件上传" style="margin: 10px"/>
</form>
<br/><br/>
<h3>文件列表</h3>
<div id="filelistdiv" style="display: none">
    <ul id="filelistul"></ul>
</div>
<h3>执行结果</h3>
<div id="result_div" style="display: none">
    <ul id="reslut_ul"></ul>
</div>
</body>
<script src='/static/assets/js/jquery-2.0.3.min.js'></script>


<script>
    $("#ajaxUpload").on('click',function() {

        let form=document.getElementById("form2")[0];
        let formData = new FormData(form);
        $.ajax({
            url:"/test/import_jxl",  //上传的url
            data:formData,
            dataType:"json",  //指定返回的格式为json
            type:"post",
            contentType: false, // 不要去设置Content-Type请求头
            processData: false, // 不要去处理发送的数据
            success:function (data) {
                for (let i = 0; i < data.message.length; i++) {
                    $("#reslut_ul").append("<li>"+ data.message[i] + "</li>")
                }
                $("#result_div").show();
            }
        })
    });

    function fileFormSelectChange(){
        let files=document.getElementById("formfile").files;
        document.getElementById("ajaxfile").value='';

        setfilelist(files);
    }

    function fileAjaxSelectChange(){
        let files=document.getElementById("ajaxfile").files;
        document.getElementById("formfile").value='';
        setfilelist(files);
    }
    function setfilelist(files) {
        $("#filelistul").html("");
        $("#reslut_ul").html("");
        if (files != undefined) {
            for (let i = 0; i < files.length; i++) {
                if (files[i]) {
                    let file = files[i];
                    let filesize=0;
                    if (file.size > 1024*1024){
                        filesize = (Math.round(file.size*100/(1024*1024)/100)).toString()+'MB';
                    } else{
                        filesize = (Math.round(file.size*100/1024/100)).toString()+'KB';
                        $("#filelistul").append("<li>文件名: "+ file.name +" ,文件大小: " +filesize + "</li>")
                    }
                }
            }
            $("#filelistdiv").show();
        }
    }
</script>
</html>